// -*- coding: utf-8 -*- 
/**
 * Project: AlgorithmsLearn
 *
 * @author: yanking
 * Create time: 2022-03-16 15:06
 * IDE: IntelliJ IDEA
 * Introduction:
 */
package com.LeetCodeT.ArraysTrain;

import org.junit.jupiter.api.Test;

import java.util.HashMap;

public class MajorityElement {
    public int majorityElementT(int[] nums) {
        HashMap<Integer, Integer> repo = new HashMap<>();
        int max = 0, res = 0;
        for (int i = 0; i < nums.length; i++) {
            repo.put(nums[i], repo.getOrDefault(nums[i], 0) + 1);
            if (max < Math.max(max, repo.get(nums[i]))) {
                max = Math.max(max, repo.get(nums[i]));
                res = nums[i];
            }
        }
        return res;
    }

    /**
     * 使用线性空间复杂度寻找主要元素
     *
     * @param nums
     * @return
     */
    public int majorityElement(int[] nums) {
        int cur = 1, res = nums[0];
        int n = nums.length;
        for (int i = 1; i < n; i++) {
            if (nums[i] == res) {
                cur++;
            } else {
                cur--;
            }
            if (cur <= 0) {
                res = nums[i];
                cur = 1;
            }
        }
        return res;
    }

    @Test
    public void shout() {
        int[] test = {8, 8, 7, 7, 7};
        System.out.println(majorityElement(test));
    }
}
